﻿@{
    ViewBag.Title = "添加销售出库单据";
    Layout = null;
}

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>采购入库单添加</title>
    <link href="~/lib/hiprint/css/hiprint.css" rel="stylesheet" />
    <link href="~/lib/hiprint/css/print-lock.css" rel="stylesheet" />
    <link href="~/lib/hiprint/content/bootstrap.min.css" rel="stylesheet">
    <script src="~/lib/jquery/dist/jquery.min.js"></script>
    <script src="~/lib/hiprint/content/bootstrap.min.js"></script>
    <!-- 引用Layui的CSS -->
    <link href="//unpkg.com/layui@2.10.1/dist/css/layui.css" rel="stylesheet">
    <style>
        /* 整体表单容器样式 */
        .order-form-container {
            padding: 10px;
        }

        .layui-column {
            display: flex;
            flex: 1;
            flex-direction: column;
            margin-right: 10px;
        }
        /* 表单行样式 */
        .layui-inline {
            display: flex;
            flex-direction: row;
            margin-bottom: 10px;
        }

        input, select {
            width: 160px; /* 调整输入框和选择框宽度 */
        }
        /* 操作按钮容器样式 */
        .operation-buttons {
            text-align: right;
            margin-bottom: 10px;
        }
        /* 表格样式 */
        .layui-table {
            width: 100%;
        }
        /* 禁用按钮样式 */
        .layui-btn[disabled] {
            opacity: 0.6; /* 背景颜色变浅 */
            cursor: not-allowed; /* 鼠标指针变为禁止图标 */
        }

            /* 禁用按钮悬停样式 */
            .layui-btn[disabled]:hover {
                position: relative;
            }

                /* 禁用按钮悬停时显示禁止图标 */
                .layui-btn[disabled]:hover::after {
                    content: '✖';
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    color: red;
                    font-size: 20px;
                }
    </style>
</head>

<body>
    <div class="order-form-container">
        <!-- 操作按钮 -->
        <div class="operation-buttons">
             <button class="layui-btn layui-btn-normal" id="approveButton">审核</button>
            <button class="layui-btn layui-bg-purple" id="reapproveButton">反审核</button>
            <button id="A4_directPrint" class="btn hiprint-toolbar-item " style="color: #fff;
    background-color: #d9534f;
    border-color: #d43f3a;">
                打印
            </button>
        </div>
        <!-- 表单信息 -->
        <div style="display:flex;flex-wrap:wrap;width:100%;">
            <div class="layui-column">
                <div class="layui-inline">
                    <label class="layui-input-inline">单据编码:</label>
                    <input type="text" id="id" class="layui-input-inline" disabled>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">业务类型:</label>
                    <div class="layui-input-inline">
                        <select id="businessType" disabled>
                            <option value="1">销售订单</option>
                            <option value="2">采购入库</option>
                            <option value="3">销售出库</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">期间:</label>
                    <input type="date" id="qiJianDate" class="layui-input-inline">
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">操作员:</label>
                    <input type="text" id="oprator" class="layui-input-inline" disabled>
                </div>
            </div>
            <div class="layui-column">
                <div class="layui-inline">
                    <label class="layui-input-inline">单据日期:</label>
                    <input type="date" id="documentDate" class="layui-input-inline" disabled>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">业务状态:</label>
                    <div class="layui-input-inline">
                        <select id="businessStatus" disabled>
                            <option value="1">正常</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">仓库:</label>
                    <select id="repository" disabled>
                        <option value="1">原材料仓库</option>
                        <option value="2">在制品仓库</option>
                        <option value="3">成品仓库</option>
                        <option value="4">保税仓库</option>
                        <option value="5">危险品仓库</option>
                    </select>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">供方</label>
                    <input type="text" id="supplyUser" class="layui-input-inline"  disabled/>
                </div>
            </div>
            <div class="layui-column">
                <div class="layui-inline">
                    <label class="layui-input-inline">审核日期:</label>
                    <input type="date" id="examDate" class="layui-input-inline">
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">业务部门:</label>
                    <div class="layui-input-inline">
                        <select id="businessDempt" disabled>
                            <option value="1">战略咨询部门</option>
                            <option value="2">财务咨询部门</option>
                            <option value="3">财务营销部门</option>
                            <option value="4">IT信息技术部门</option>
                            <option value="5">人力资源部门</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">到货单号:</label>
                    <input type="text" id="arivalNumber" class="layui-input-inline" disabled>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">备注信息:</label>
                    <input type="text" id="remark" class="layui-input-inline" disabled>
                </div>
            </div>
            <div class="layui-column">
                <div class="layui-inline">
                    <label class="layui-input-inline">单据类型:</label>
                    <select id="documentType" class="layui-input-inline" disabled>
                        <option value="1">销售订单</option>
                        <option value="2">采购入库单</option>
                        <option value="3">销售出库单</option>
                    </select>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">单据状态:</label>
                    <select id="documentStatus" class="layui-input-inline" disabled>
                        <option value="0">开立</option>
                        <option value="1">退回</option>
                        <option value="2">审核</option>
                    </select>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">业务人员:</label>
                    <input type="text" id="businessUser" class="layui-input-inline" disabled>
                </div>
                <div class="layui-inline">
                    <label class="layui-input-inline">审批人:</label>
                    <select id="examUserName" disabled>
                      
                    </select>
                </div>
            </div>
        </div><br />
        <!-- 表单信息表格操作按钮 -->
        <div class="form-row">
            @* <button class="layui-btn layui-btn-xs" id="importButton">引入</button> *@
            <button class="layui-btn layui-btn-xs" id="addMaterialButton">新增物料</button>
        </div>

        <!-- 表单信息表格 -->
        <table class="layui-table" id="materialTable">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>物料编码</th>
                    <th>物料名称</th>
                    <th>型号规格</th>
                    <th>主计量</th>
                    <th>出库数量</th>
                    <th>批号</th>
                    <th>质量要求</th>
                    <th>备注</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    <!--[[ 打印 -->
    <script src="~/lib/hiprint/custom_test/custom-etype-provider.js"></script>
    <script src="~/lib/hiprint/custom_test/purchaseIn-print-json.js"></script>
    <script src="~/lib/hiprint/custom_test/print-data.js"></script>
    <script src="~/lib/hiprint/polyfill.min.js"></script>
    <script src="~/lib/hiprint/plugins/jquery.minicolors.min.js"></script>
    <script src="~/lib/hiprint/plugins/JsBarcode.all.min.js"></script>
    <script src="~/lib/hiprint/plugins/qrcode.js"></script>
    <script src="~/lib/hiprint/hiprint.bundle.js"></script>
    <script src="~/lib/hiprint/plugins/jquery.hiwprint.js"></script>
    <script src="//unpkg.com/layui@2.10.1/dist/layui.js"></script>
    <script>
        layui.use(['layer', 'form', 'jquery'], function () {
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.jquery;
            var documentCode = "";
            var currentUserName = "";
            var hiprintTemplate;
            // 从URL获取单据编码
            function getQueryParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return decodeURIComponent(r[2]);
                return null;
            }
            // 初始化一个空行
            function initEmptyRow() {
                return {
                    materialsCode: 660376998223878,
                    materialsName: 'A4纸',
                    modelSpecification: '',
                    calulate: '箱',
                    outBoundNumber: 0,
                    batch: '',
                    qualityRequir: '',
                    remark: '',
                    materialsClass: 2
                };
            }
            // 清空物料表格
            function clearMaterialTable() {
                $('#materialTable tbody').empty();
            }
            // 添加物料行
            function addMaterialRow(material) {
                material = material || initEmptyRow();
                var rowCount = $('#materialTable tbody tr').length + 1;

                var rowHtml = `
                                                 <tr data-index="${rowCount - 1}">
                                                                            <td>${rowCount}</td>
                                                                            <td>
                                                                                        <input type="text" class="layui-input materialsCode" value="${material.materialsCode}" id="materialsCode" placeholder="物料编码" readonly>
                                                                                <button type="button" class="layui-btn layui-btn-xs selectMaterialButton">选择</button>
                                                                            </td>
                                                                                    <td><input type="text" class="layui-input materialsName" value="${material.materialsName}" id="materialsName" placeholder="物料名称" readonly></td>
                                                                                                    <td><input type="text" class="layui-input" value="${material.modelSpecification}" id="modelSpecification" placeholder="型号规格"></td>
                                                                            <td>
                                                                                        <select class="layui-select calulate" id="calulate">
                                                                                    <option value="台" ${material.calulate === '台' ? 'selected' : ''}>台</option>
                                                                                    <option value="箱" ${material.calulate === '箱' ? 'selected' : ''}>箱</option>
                                                                                    <option value="张" ${material.calulate === '张' ? 'selected' : ''}>张</option>
                                                                                    </select>
                                                                            </td>
                                                                                    <td><input type="number" class="layui-input outBoundNumber" id="outBoundNumber" value="${material.outBoundNumber}" placeholder="出库数量"></td>
                                                                                    <td><input type="text" class="layui-input batch" id="batch" value="${material.batch}" placeholder="批号"></td>
                                                                                    <td><input type="text" class="layui-input qualityRequir" id="qualityRequir" value="${material.qualityRequir}" placeholder="质量要求"></td>
                                                                                    <td><input type="text" class="layui-input remark" id="remark" value="${material.remark}" placeholder="备注"></td>

                                                                        </tr>`;

                $('#materialTable tbody').append(rowHtml);
                form.render();
            }
            // 加载销售出库单据详情
            function loadOrderDetail(documentCode) {
                console.log("加载销售出库单据详情", documentCode);
                if (!documentCode) return;
                var loadIndex = layer.load(2);
                $.ajax({
                    url: 'http://localhost:5234/api/PurchaseInRepository/GetPurchaseInRepositoryDetail',
                    //url: "@ViewBag.BaseUrl/T7/PurchaseInRepository/GetPurchaseInRepositoryDetail",
                    type: 'GET',
                    data: { DocumentCode: documentCode },
                    dataType: 'json',
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.code === 210 && res.data) {
                            fillFormData(res.data);
                        } else {
                            layer.msg(res.msg || '获取订单详情失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.close(loadIndex);
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error(xhr.responseText);
                    }
                });
            }

            // 填充表单数据
            function fillFormData(data) {
                // 基本信息
                $('#id').val(data.id);
                $('#oprator').val(data.oprator);
                $('#qiJianDate').val(formatDate(data.qiJianDate));
                $('#repository').val(data.repository);
                $('#arivalNumber').val(data.arivalNumber);
                $('#documentDate').val(formatDate(data.documentDate));
                $('#examDate').val(formatDate(data.examDate));
                $('#businessStatus').val(data.businessStatus);
                $('#documentStatus').val(data.documentStatus);
                $('#documentType').val(data.documentType);
                $('#businessDempt').val(data.businessDempt);
                $('#examUserName').val(data.examUserName);
                $('#businessDemptName').val(data.businessDemptName);
                $('#remark').val(data.remark);
                $('#businessType').val(data.businessType);
                $('#supplyUser').val(data.supplyUser);
                $('#businessUser').val(data.businessUser);
                // 渲染表单
                form.render();

                // 填充物料数据
                clearMaterialTable();
                if (data.orderMaterials && data.orderMaterials.length > 0) {
                    data.orderMaterials.forEach(function (material) {
                        addMaterialRow(material);
                    });
                } else {
                    addMaterialRow(); // 添加一个空行
                }
                console.log("data.examUserName", data.examUserName);
                // 判断并控制按钮禁用状态
                if (currentUserName && data.examUserName) {
                    if (currentUserName == data.examUserName) {
                        switch (data.documentStatus) {
                            case 0: // 开立状态 可审核 不可反审核
                                $('#approveButton').prop('disabled', false);
                                $('#reapproveButton').prop('disabled', true);
                                break;
                            case 2: // 审核状态 可反审核 不可审核
                                $('#approveButton').prop('disabled', true);
                                $('#reapproveButton').prop('disabled', false);
                                break;
                            case 1: // 退回状态 不可反审核 不可审核
                                $('#approveButton').prop('disabled', true);
                                $('#reapproveButton').prop('disabled', true);
                                break;
                            default:
                                // 可以添加默认情况，比如未知状态都禁用按钮
                                $('#approveButton').prop('disabled', true);
                                $('#reapproveButton').prop('disabled', true);
                        }
                    } else {
                        // 当前用户不是审核人，都禁用
                        $('#approveButton').prop('disabled', true);
                        $('#reapproveButton').prop('disabled', true);
                    }
                } else {
                    // 没有当前用户信息或者审核人信息，都禁用
                    $('#approveButton').prop('disabled', true);
                    $('#reapproveButton').prop('disabled', true);
                }
            }

            // 格式化日期为YYYY-MM-DD
            function formatDate(dateString) {
                if (!dateString) return '';
                var date = new Date(dateString);
                return date.getFullYear() + '-' +
                    String(date.getMonth() + 1).padStart(2, '0') + '-' +
                    String(date.getDate()).padStart(2, '0');
            }
            //审核操作
            $("#approveButton").click(function () {
                layer.confirm('修改单据状态是审核还是退回？', {
                    btn: ['审核', '退回'] // 按钮文本
                }, function (index) { // 点击确定后的回调
                    var applyData = { id: documentCode, examPersonName: currentUserName, examStatus: 2 };
                    $.ajax({
                        url: 'http://localhost:5090/api/PurchaseInRepository/ApplyPurchaseInStore',
                        //url: "@ViewBag.BaseUrl/T8/PurchaseInRepository/ApplyPurchaseInStore",
                        type: 'post',
                        contentType: 'application/json',
                        data: JSON.stringify(applyData),
                        dataType: 'json',
                        success: function (res) {
                            if (res.code === 206 && res.data) {
                                location.href = "/PurchaseInRepository/GetPurchaseInStore";
                            } else {
                                layer.msg(res.msg || '修改单据状态失败', { icon: 2 });
                            }
                        },
                        error: function (xhr, status, error) {
                            layer.close(loadIndex);
                            layer.msg('请求失败: ' + error, { icon: 2 });
                            console.error(xhr.responseText);
                        }
                    });
                    layer.close(index); // 关键：关闭当前弹窗
                }, function (index) {
                    var applyData = { id: documentCode, examPersonName: currentUserName, examStatus: 1 };
                    $.ajax({
                       url: 'http://localhost:5090/api/PurchaseInRepository/ApplyPurchaseInStore',
                        //url: "@ViewBag.BaseUrl/T8/PurchaseInRepository/ApplyPurchaseInStore",
                        type: 'post',
                        contentType: 'application/json',
                        data: JSON.stringify(applyData),
                        dataType: 'json',
                        success: function (res) {
                            if (res.code === 206 && res.data) {
                                location.href = "/PurchaseInRepository/GetPurchaseInStore";
                            } else {
                                layer.msg(res.msg || '修改单据状态失败', { icon: 2 });
                            }
                        },
                        error: function (xhr, status, error) {
                            layer.close(loadIndex);
                            layer.msg('请求失败: ' + error, { icon: 2 });
                            console.error(xhr.responseText);
                        }
                    });
                    layer.close(index); // 关键：关闭当前弹窗
                });
            })
            //反审核操作
            $("#reapproveButton").click(function () {
                layer.confirm('确定修改单据状态是开立吗？', {
                    btn: ['确定', '取消'] // 按钮文本
                }, function (index) { // 点击确定后的回调
                    var applyData = { id: documentCode, examPersonName: currentUserName, examStatus: 0 };
                    $.ajax({
                       url: 'http://localhost:5090/api/PurchaseInRepository/ApplyPurchaseInStore',
                        //url: "@ViewBag.BaseUrl/T8/PurchaseInRepository/ApplyPurchaseInStore",
                        type: 'post',
                        contentType: 'application/json',
                        data: JSON.stringify(applyData),
                        dataType: 'json',
                        success: function (res) {
                            if (res.code === 206 && res.data) {
                                location.href = "/PurchaseInRepository/GetPurchaseInStore";
                            } else {
                                layer.msg(res.msg || '修改单据状态失败', { icon: 2 });
                            }
                        },
                        error: function (xhr, status, error) {
                            layer.close(loadIndex);
                            layer.msg('请求失败: ' + error, { icon: 2 });
                            console.error(xhr.responseText);
                        }
                    });
                    layer.close(index); // 关键：关闭当前弹窗
                }, function (index) {
                    layer.close(index); // 取消时也关闭弹窗
                });
            })
            // 页面初始化
            $(function () {
                // 获取审批人数据并填充下拉框
                $.ajax({
                    url: 'https://localhost:7174/api/Message/GetUser',
                    //url: "@ViewBag.BaseUrl/T5/Message/GetUser",
                    type: 'GET',
                    success: function (res) {
                        if (res.code === 210) {
                            var users = res.data;
                            var options = '';
                            users.forEach(function (user) {
                                options += `<option value="${user.userName}">${user.userName}</option>`;
                            });
                            $('#examUserName').html(options);
                            form.render('select');
                        } else {
                            layer.msg(res.msg || '获取用户数据失败', { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error(xhr.responseText);
                    }
                });
                //初始化打印插件
                hiprint.init({
                    providers: [new customElementTypeProvider()]
                });
                hiprintTemplate = new hiprint.PrintTemplate({
                    template: customPrintJson,
                    settingContainer: '#PrintElementOptionSetting',
                    paginationContainer: '.hiprint-printPagination'
                });
                //获取当前登录人所有信息
                currentUserName = localStorage.getItem('userData');
                console.log("在采购入库打印当前登录人的所有信息currentUserData", currentUserName);
                // 获取单据编码并加载数据
                documentCode = getQueryParam('id');
                console.log("22222查看销售出库编码22222：", documentCode);
                if (documentCode) {
                    loadOrderDetail(documentCode);
                } else {
                    // 新增模式，初始化一个空行
                    addMaterialRow();
                }
                //打印
                // 使用$.ajax获取接口数据
                $.ajax({
                    url: 'http://localhost:5234/api/PurchaseInRepository/GetPurchaseInRepositoryDetail',
                    //url: "@ViewBag.BaseUrl/T7/PurchaseInRepository/GetPurchaseInRepositoryDetail",
                    type: 'GET',
                    data: { DocumentCode: documentCode },
                    dataType: 'json',
                    success: function (response) {
                        if (response.code === 210) {
                            var printData = response.data;
                            // 这里可以根据需要对printData进行进一步处理或传递给打印函数
                            // 例如，重新定义打印相关按钮的点击事件处理函数，使用新获取的数据
                            $('#A4_preview').click(function () {
                                $('#myModal .modal-body .prevViewDiv').html(hiprintTemplate.getHtml(printData))
                                $('#myModal').modal('show')
                            });
                            $('#A4_directPrint').click(function () {
                                hiprintTemplate.print(printData);
                            });
                            $('#A4_printByHtml').click(function () {
                                hiprintTemplate.printByHtml($('#myModal .modal-body .prevViewDiv'));
                            })
                        } else {
                            console.log('获取数据失败:', response.msg);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('请求出错:', error);
                    }
                });
            });
        });
    </script>
</body>
</html>